package com.example.InetAddressDemos.udp.broadcastMode;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * @author Jason
 * @PACKAGE_NAME com.example.InetAddressDemos.udp.broadcastMode
 * @Description 组播接收端代码
 * @date 2023-12-18 17:50
 */
public class udpMulticastReceiver1 {
    public static void main(String[] args) throws IOException {
        /*
        组播接收端代码
         */

        //创建MulticastSocket对象
        MulticastSocket ms = new MulticastSocket(10000);

        //将当前本机。添加到224.0.0.1这一组中
        InetAddress address = InetAddress.getByName("224.0.0.1");
        ms.joinGroup(address);

        //创建DatagramPackey数据包对象
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

        //调用MulticastSocket接收数据
        ms.receive(dp);

        //解析数据
        byte[] data = dp.getData();
        int len = dp.getLength();
        String ip = dp.getAddress().getHostAddress();
        String name = dp.getAddress().getHostName();

        System.out.println("IP为" + ip + "，主机名为" + name + "的人，发送了数据" + new String(data, 0, len));


        //释放资源
        ms.close();
    }
}
